package com.bayss.core.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.bayss.core.model.ContentDetailVo;
import com.bayss.core.model.ContentVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * 文件工具类
 * @author yangjian9
 *
 */
public class FileUtil {

    private FileUtil(){}

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    private static OSS ossClient = new OSSClientBuilder().build("https://oss-cn-beijing.aliyuncs.com", "LTAI4FjvBA5HR1Yk4xf6AERV", "oKL3jHhk4pX4nL8rZrvHuNPSkyhC0C");

    public static String imgUrl(String key){
        if (StringUtils.isEmpty(key)) {
            return key;
        }
        URL url = ossClient.generatePresignedUrl("doko-way" , key, new Date(System.currentTimeMillis()+1000*60*30));
        return url.toString();
    }

    /**
     * json对象中的url字段
     * @param value
     * @return
     */
    public static String jsonDataImgUrl(String value) {
        try {
            ContentVo contentVo = JSONObject.parseObject(value, ContentVo.class);
            for (ContentDetailVo d : contentVo.getUploadImg()) {
                d.setUrl(imgUrl(d.getUrl()));
            }
            return JSONObject.toJSONString(contentVo);
        } catch (Exception e) {
            logger.error("解析字段中image url失败 : ", value);
        }
        return value;
    }
    public static String formatImgUrl(String key){
        if (StringUtils.isEmpty(key)) {
            return key;
        }

        if (key.startsWith("http") || key.startsWith("https")) {
            int start = key.indexOf("com/doko")+4;
            int end = key.indexOf("?");
            key = key.substring(start, end);
        }
        return key;
    }

    public static boolean writeFile(String path, String name, InputStream input){
        // 设置数据缓冲
        byte[] bs = new byte[1024 * 2];
        // 读取到的数据长度
        int len;
        // 输出的文件流保存图片至本地
        OutputStream os = null;

        String inputPath = "";

        try {
            File sf=new File(path);
            if(!sf.exists()){
                sf.mkdirs();
            }

            inputPath = path+"/"+name;
            os = new FileOutputStream(inputPath);
            while ((len = input.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException : ", e);
            return false;
        } catch (IOException e) {
            logger.error("IOException : ", e);
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (input != null) {
                    input.close();
                }
            }catch (IOException e){
                logger.error("writeFile close is error: " + e);
            }
        }
        return true;
    }

    /**
     * 删除单个文件
     *
     * @param path 要删除的文件的路径与名称
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String path) {
        try {
            File file = new File(path);
            // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
            if (file.exists()) {
                if (file.isFile()) {
                    return file.delete();
                } else {
                    return false;
                }
            }
        }catch (Exception e){
            logger.error("deleteFile is error: " + e);
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        imgUrl("doko-admin/1578470132478WX20191118-110352%402x.jpg");
    }


}
